﻿namespace Away.Common.Mvc.Controllers;

public class ApiResult : ObjectResult
{
    public int Code { get; private set; }
    public string Message { get; private set; } = null!;
    public bool Success => Code == 0;

    public ApiResult(object? value) : base(value)
    {
        if (value is ApiResultModel result)
        {
            Code = result.Code;
            Message = result.Message;
        }
    }


    public static ApiResult Data(object value)
    {
        return new ApiResult(value);
    }

    public static ApiResult Page<T>(int total, List<T> items)
    {
        return Ok(new PageResultModel<T>()
        {
            Total = total,
            Items = items
        });
    }

    public static ApiResult Ok(int code = 0, string message = "")
    {
        var result = new ApiResultModel { Code = code, Message = message };
        return Data(result);
    }

    public static ApiResult Ok<T>(T data, int code = 0, string message = "")
    {
        var result = new ApiResultModel<T> { Code = code, Message = message, Result = data };
        return Data(result);
    }
}

public class ApiResultModel
{
    private string _msg = string.Empty;

    /// <summary>
    /// 状态码 0成功
    /// </summary>
    public int Code { get; set; }

    /// <summary>
    /// 说明
    /// </summary>
    public string Message
    {
        get => string.IsNullOrWhiteSpace(_msg) ? string.Empty : _msg.Trim();
        set => _msg = value;
    }

    public bool Success => Code == 0;

    public ApiResultModel() { }
}

public class ApiResultModel<T> : ApiResultModel
{
    /// <summary>
    /// 数据
    /// </summary>
    public required T Result { get; set; }

    public ApiResultModel() { }
}

public class PageResultModel<T>
{
    private List<T> _items = new();

    public int Total { get; set; }
    public List<T> Items
    {
        get => _items ?? new List<T>();
        set => _items = value;
    }

    public PageResultModel() { }
}

